package com.contant;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.tunan.common.Result;
import com.tunan.lsj.validator.IServerCheckHandler;
import com.tunan.system.persistence.model.SpringContextUtil;

public class ValidateBridge {
	public static synchronized Result validate(String[]  validators,Object m,String[] proppertyarr,String userId){
		Map map = new HashMap();
		if(m instanceof Map){
			map=(Map)m;
		}else{
			map=convertBean(m);
		}
		for (int i = 0; i < validators.length; i++) {
			IServerCheckHandler sc=(IServerCheckHandler)SpringContextUtil.getBean(validators[i]);
			String property=null;
			if(proppertyarr!=null&&proppertyarr[i]!=null)
				property=proppertyarr[i];
			Result result=	sc.verify(property, map, userId);
			if(!result.isSuccess())
				return result;
		}
		return new Result();
	}
	public static Map convertBean(Object bean){
		Map returnMap = new HashMap();
		try {
			Class type = bean.getClass();
			BeanInfo beanInfo = Introspector.getBeanInfo(type);
			
			PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
			for (int i = 0; i< propertyDescriptors.length; i++) {
				PropertyDescriptor descriptor = propertyDescriptors[i];
				String propertyName = descriptor.getName();
				if (!propertyName.equals("class")) {
					Method readMethod = descriptor.getReadMethod();
					Object result = readMethod.invoke(bean, new Object[0]);
					if (result != null) {
						returnMap.put(propertyName, result);
					} else {
						returnMap.put(propertyName, "");
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
        return returnMap;
    }
}
